package tsli.acm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import tsli.acm.dao.PersistencyDAO;
import tsli.acm.dao.RententionDAO;
import tsli.acm.dao.SFCAgentStructureDAO;
import tsli.acm.dao.SFCCommissionNegativeDAO;
import tsli.acm.dao.SFCCommissionPositiveDAO;
import tsli.acm.database.Database;

/**
 * Servlet implementation class ACM1203Srvl
 */
public class ACM1203Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DecimalFormat voDecimalFormat = new DecimalFormat("#,###,###.00");
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ACM1203Srvl() {
        super();
    }
    
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String vaProcessType = request.getParameter("process_type");
		if (vaProcessType != null && vaProcessType.equals("getDataTable")) {
			getDataTable(request, response);
		} else if ( vaProcessType != null && vaProcessType.equals("calculateIncentive")){
			calculateIncentive(request, response);
		} else if ( vaProcessType != null && vaProcessType.equals("calculateOE")){
			calculateOE(request, response);
		}  else if ( vaProcessType != null && vaProcessType.equals("getDetailPCDataTable")){
			getDataTableDetailPC(request, response);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void calculateIncentive (HttpServletRequest request, HttpServletResponse response) throws IOException {
		// get parameter
		String vaPeNoMM = request.getParameter("paPeNoMM");
		String vaClosYm = request.getParameter("paCloYM");
		// new database
		Database db = new Database();
		SFCCommissionPositiveDAO voSFCCommissionPositiveDAO = new SFCCommissionPositiveDAO(db);
		SFCCommissionNegativeDAO voSFCCommissionNegativeDAO = new SFCCommissionNegativeDAO(db);
		PersistencyDAO voPersistencyDAO = new PersistencyDAO(db);
		RententionDAO voRententionDAO = new RententionDAO(db);
		DecimalFormat df = new DecimalFormat("#,##0.00");
		// variable
		String[] voAllSumResult = null;
		Double[] voAllOE = null;
		double vnPc = 0.0 , vnPaymentRate = 0.0 , vnPersistencyModify = 0.0 , vnRetentionRatio = 0.0, vnTotal = 0.0, vnNormalTotal = 0.0 , vnRecalTotal = 0.0 ,vnNetMM = 0.0; ;
		String vaGraderAmount = "", vaPersistencyAmount = "", vaRetentionRatioAmount = "", vaPC ="", vaRemark ="", vaHasData = "yes", vaStatusAllOE = "yes";
		// find fee look in current month
		String vaFeeLook = voSFCCommissionNegativeDAO.findFeeLookInMount(vaPeNoMM, vaClosYm);
		// Case : fee look not exist
		if (vaFeeLook.equals("0")){
			// find PC
			vaPC = voSFCCommissionPositiveDAO.findPcOfMM(vaPeNoMM, vaClosYm);			
			vnPc = Double.parseDouble( vaPC.replaceAll(",", ""));
			// find payment rate
			String vaDataQuery = voSFCCommissionPositiveDAO.findPaymentRate( vaPeNoMM,vaClosYm);	
			String[] voDataSplit = vaDataQuery.split("/");
			vnPaymentRate = Double.parseDouble( voDataSplit[0]);			
			vaGraderAmount = voDataSplit[1];
			// find Persistency
			String vaDataQuery2 = voPersistencyDAO.getPersistencyModifyFOrMM(vaPeNoMM,vaClosYm);
			String[] voPersistencyModifySplit = vaDataQuery2.split("/");
			vaPersistencyAmount = voPersistencyModifySplit[1];	
			vnPersistencyModify = Double.parseDouble(voPersistencyModifySplit[0]);	
			
			if ( vaPC.equals("0") && voDataSplit[2].equals("0") || vaPersistencyAmount.equals("nul")){
				vaHasData = "no";			
			} else {
				// find Retention
				String vaDataQuery3 = voRententionDAO.getRetentionRatioByForMM(vaClosYm);
				String[] voRetentionRatioSplit = vaDataQuery3.split("/");
				vnRetentionRatio = Double.parseDouble( voRetentionRatioSplit[0]);
				vaRetentionRatioAmount = voRetentionRatioSplit[1];					
				// total OE
				vnTotal = vnPc * vnPaymentRate * vnPersistencyModify * vnRetentionRatio;	
			}
			voAllSumResult = new String[]{vaHasData,"1",vaPC,vaGraderAmount,vaPersistencyAmount+"%",vaRetentionRatioAmount+"%",
					vaPC+" x "+ (int) (vnPaymentRate*100) +"%"+" x "+ (int)( vnPersistencyModify*100)+"%"+" x "+ (int)(vnRetentionRatio*100)+"%",String.valueOf(df.format(vnTotal))};
			vaStatusAllOE = "no";
		} else {
			//get Normal calculator
			// find PC
			String vaPC1 = voSFCCommissionPositiveDAO.findPcOfMM(vaPeNoMM, vaClosYm);			
			double vnPc1 = Double.parseDouble( vaPC1.replaceAll(",", ""));
			// find payment rate
			String vaDataQuery1 = voSFCCommissionPositiveDAO.findPaymentRate( vaPeNoMM,vaClosYm);	
			String[] voDataSplit1 = vaDataQuery1.split("/");
			vnPaymentRate = Double.parseDouble( voDataSplit1[0]);			
			vaGraderAmount = voDataSplit1[1];
			// find Persistency
			String vaDataQuery4 = voPersistencyDAO.getPersistencyModifyFOrMM(vaPeNoMM,vaClosYm);
			String[] voPersistencyModifySplit1 = vaDataQuery4.split("/");
			vaPersistencyAmount = voPersistencyModifySplit1[1];	
			vnPersistencyModify = Double.parseDouble(voPersistencyModifySplit1[0]);	
			double vnMMNormal = 0.0;
			if ( vaPC.equals("0") && voDataSplit1[2].equals("0") || vaPersistencyAmount.equals("nul")){
				vaHasData = "no";			
			} else {
				// find Retention
				String vaDataQuery5 = voRententionDAO.getRetentionRatioByForMM(vaClosYm);
				String[] voRetentionRatioSplit1 = vaDataQuery5.split("/");
				vnRetentionRatio = Double.parseDouble( voRetentionRatioSplit1[0]);
				vaRetentionRatioAmount = voRetentionRatioSplit1[1];					
				// total OE
				vnMMNormal = vnPc1 * vnPaymentRate * vnPersistencyModify * vnRetentionRatio;	
			}
			
			// Case : fee look exist
			// find fee look in month
			List<Map<String, Object>> vaClosYmList = voSFCCommissionPositiveDAO.findClosYmOfFeeLook(vaPeNoMM, vaClosYm);
			// find PC
			vaPC = voSFCCommissionPositiveDAO.findPcOfMM(vaPeNoMM, vaClosYm);
			// new Array for OE
			voAllOE = new Double[vaClosYmList.size()];
			for (int i = 0; i < vaClosYmList.size(); i++){
				Map<String, Object> voObject = vaClosYmList.get(i);
				String vaClosYmOfFeeLook = voObject.get("CLOS_YM").toString();
				// normal calculate MM 
				// find PC
				String vaNormalPC = voSFCCommissionPositiveDAO.findPcOfMM(vaPeNoMM, vaClosYmOfFeeLook);		
				String vaFeeLookPc = voSFCCommissionNegativeDAO.findFeeLookPcOfMM(vaPeNoMM, vaClosYm);
				double vnNetPc = Double.parseDouble(vaNormalPC.replaceAll(",", "")) - Double.parseDouble(vaFeeLookPc.replaceAll(",", ""));
				// find payment rate
				String vaDataQuery = voSFCCommissionPositiveDAO.findPaymentRate( vaPeNoMM,vaClosYmOfFeeLook);	
				String[] voDataSplit = vaDataQuery.split("/");
				vnPaymentRate = Double.parseDouble( voDataSplit[0]);			
				vaGraderAmount = voDataSplit[1];
				// find Persistency
				String vaDataQuery2 = voPersistencyDAO.getPersistencyModifyFOrMM(vaPeNoMM,vaClosYmOfFeeLook);
				String[] voPersistencyModifySplit = vaDataQuery2.split("/");
				vnPersistencyModify = Double.parseDouble(voPersistencyModifySplit[0]);	
				vaPersistencyAmount = voPersistencyModifySplit[1];	
				
				if ( vaNormalPC.equals("0") && voDataSplit[1].equals("0") || vaPersistencyAmount.equals("nul")){
					vaHasData = "no";			
				} else {
					// find Retention
 					String vaDataQuery3 = voRententionDAO.getRetentionRatioByForMM(vaClosYmOfFeeLook);
					String[] voRetentionRatioSplit = vaDataQuery3.split("/");
					vnRetentionRatio = Double.parseDouble( voRetentionRatioSplit[0]);
					vaRetentionRatioAmount = voRetentionRatioSplit[1];					
					// total OE
					vnNormalTotal = Double.parseDouble(vaNormalPC.replaceAll(",", "")) * vnPaymentRate * vnPersistencyModify * vnRetentionRatio;	
					vnRecalTotal = (Double.parseDouble(vaNormalPC.replaceAll(",", "")) - Double.parseDouble(vaFeeLookPc.replaceAll(",", ""))) * vnPaymentRate * vnPersistencyModify * vnRetentionRatio;	
				}
				voAllOE[i] = vnNormalTotal - vnRecalTotal;
			}
			
			vnNetMM = vnMMNormal;
			for(int i = 0; i < voAllOE.length ;i++ ){
				vnNetMM = vnNetMM - voAllOE[i];
			}
			
//			RecalInMonth voRecalInMonth = new RecalInMonth();
			voAllSumResult = new String[]{vaHasData,"1",vaPC,vaGraderAmount,vaPersistencyAmount+"%",vaRetentionRatioAmount+"%",
			vaPC+" x "+ (int) (vnPaymentRate*100) +"%"+" x "+ (int)( vnPersistencyModify*100)+"%"+" x "+ (int)(vnRetentionRatio*100)+"%",String.valueOf(df.format(vnMMNormal))};
		}
		// add data to JSon Object
		PrintWriter voOut = response.getWriter();
		try {
			JSONObject voObject = new JSONObject();
			JSONArray voArrayData = new JSONArray();
			JSONArray voArrayData2 = new JSONArray();
			for ( int i = 0; i < voAllSumResult.length; i++){
				voArrayData.add(voAllSumResult[i]);
			}		
			if (voAllOE != null){
				for ( int i = 0; i < voAllOE.length; i++){
					voArrayData2.add(voDecimalFormat.format(voAllOE[i]));
				}
	    		voObject.put("voAllOE",voArrayData2 );
			}
			voObject.put("voJSonResult",voArrayData );
    		voObject.put("vaRemark", vaRemark);
    		voObject.put("vaStatusAllOE", vaStatusAllOE);
    		voObject.put("vnNetMM", voDecimalFormat.format(vnNetMM));
			voOut.print(voObject.toJSONString());
		} finally {
			db.close();
			voOut.close();
		}
    }
	
    @SuppressWarnings("unchecked")
	private void calculateOE (HttpServletRequest request, HttpServletResponse response) throws IOException {
		// get Parameter
    	String vaPeNoMM = request.getParameter("paPeNoMM");
		String vaClosYm = request.getParameter("paCloYM");
		// new database
		Database db = new Database();
		SFCCommissionPositiveDAO voSFCCommissionPositiveDAO = new SFCCommissionPositiveDAO(db);
		SFCCommissionNegativeDAO voSFCCommissionNegativeDAO = new SFCCommissionNegativeDAO(db);
		PersistencyDAO voPersistencyDAO = new PersistencyDAO(db);
		SFCAgentStructureDAO voSFCAgentStructure = new SFCAgentStructureDAO(db);
		// variable
		String vaAcProducerAmount ="", vaAcProducerMoney ="", vaAcProducerData ="" , IsEmptyGraderData = "no" , IsEmptyProductionData = "no";
		double vnProductionPart = 0.0 , vnOrganizationPart = 0.0, vnTotalOE = 0.0, vnNormalTotal = 0.0 , vnRecalTotal = 0.0, vnProductionPartNormalTotal = 0.0;
		String vaTrOfTable = "", isNullData = "no", vaRemark = "", vaStatusAllOE = "yes", vaSpecialOE = "no";
		double vaProductPartPC = 0.0, vaARYP = 0.0 , vaRatio = 0.0, vaPersistency = 0.0, vnProductionPartRecalTotal = 0.0, vnNetOE = 0.0;
		Double[] voAllOE = null;
		try {
			// check new MM
			String vbIsNewMm = voSFCAgentStructure.checkNewPeNoMM(vaPeNoMM, vaClosYm);
//			vbIsNewMm = "1";
			// Organization Part
				String vaTotalGrader = voSFCCommissionPositiveDAO.findTotalGrader(vaClosYm, vaPeNoMM);			
				List<Map<String, Object>> voGraderList = voSFCCommissionPositiveDAO.findGraderList(vaClosYm, vaPeNoMM);
				vaAcProducerData = voSFCCommissionPositiveDAO.findActiveProducer(vaClosYm);
				String voProducerDataSplit[] = vaAcProducerData.split("/");
				vaAcProducerMoney  = voProducerDataSplit[0];
				vaAcProducerAmount = voProducerDataSplit[1];
				vnOrganizationPart = Double.parseDouble( vaTotalGrader) + Double.parseDouble( vaAcProducerMoney);
			
				String vaFeeLook = voSFCCommissionNegativeDAO.findFeeLookInMount(vaPeNoMM, vaClosYm);
				// Case : fee look not exist
				if (vaFeeLook.equals("0")){
					// Production Part
					vaProductPartPC =  Double.parseDouble( voSFCCommissionPositiveDAO.getSumPcForOE(vaClosYm, vaPeNoMM));
					vaARYP =  Double.parseDouble( voSFCCommissionPositiveDAO.getSumARYPForOE(vaClosYm, vaPeNoMM));
					String vnPersisAndRatio =  voPersistencyDAO.getPersisAndRatioForOE(vaClosYm, vaPeNoMM);
					String[] dataTemp = vnPersisAndRatio.split("/");
					vaPersistency = Double.parseDouble(dataTemp[0]);
					vaRatio = Double.parseDouble(dataTemp[1]);
					
					if ( vaProductPartPC != 0.0 && vaARYP != 0.0 && vaRatio != 0.0){
						vnTotalOE = ((vaProductPartPC*0.01)+(vaARYP)*0.005)*vaRatio;
						vnTotalOE = vnTotalOE + vnOrganizationPart;
					}
					
					for ( int i = 0; i < voGraderList.size() ;i++){
						Map<String, Object> voObject = voGraderList.get(i);
						String vaGrader =  voObject.get("GRADER").toString();
						String vaPersonPerGrader = voObject.get("PERSON_PER_GRADER").toString();
						int vnMoneyPerPerson = Integer.parseInt( voObject.get("MONEY_PER_PERSON").toString());
						int vnPersonPerGrader = Integer.parseInt( voObject.get("PERSON_PER_GRADER").toString());
						int vnMoney = vnMoneyPerPerson / vnPersonPerGrader;
						vaTrOfTable += "<tr><td >"+vaGrader+"</td><td >"+vaPersonPerGrader+"</td><td >"+voDecimalFormat.format(vnMoney)+"</td></tr>";
					}
					vaStatusAllOE = "no";
				} else {
					// Case : fee look exist
					// normal calculate
					vaProductPartPC =  Double.parseDouble( voSFCCommissionPositiveDAO.getSumPcForOE(vaClosYm, vaPeNoMM));
					vaARYP =  Double.parseDouble( voSFCCommissionPositiveDAO.getSumARYPForOE(vaClosYm, vaPeNoMM));
					String vnPersisAndRatio =  voPersistencyDAO.getPersisAndRatioForOE(vaClosYm, vaPeNoMM);
					String[] dataTemp = vnPersisAndRatio.split("/");
					vaPersistency = Double.parseDouble(dataTemp[0]);
					vaRatio = Double.parseDouble(dataTemp[1]);
					
					if ( vaProductPartPC != 0.0 && vaARYP != 0.0 && vaRatio != 0.0){
						vnTotalOE = ((vaProductPartPC*0.01)+(vaARYP)*0.005)*vaRatio;
						vnTotalOE = vnTotalOE + vnOrganizationPart;
					}
					
					// find fee look in month
					List<Map<String, Object>> vaClosYmList = voSFCCommissionPositiveDAO.findClosYmOfFeeLook(vaPeNoMM, vaClosYm);
					// find PC
					voAllOE = new Double[vaClosYmList.size()];
					for (int i = 0; i < vaClosYmList.size(); i++){
						Map<String, Object> voObject = vaClosYmList.get(i);
						String vaClosYmOfFeeLook = voObject.get("CLOS_YM").toString();
						// find PC
						String vaNormalPC = voSFCCommissionPositiveDAO.findPcOfMM(vaPeNoMM, vaClosYmOfFeeLook);		
						String vaFeeLookPc = voSFCCommissionNegativeDAO.findFeeLookPcOfMM(vaPeNoMM, vaClosYm);
						double vnNetPc = Double.parseDouble(vaNormalPC.replaceAll(",", "")) - Double.parseDouble(vaFeeLookPc.replaceAll(",", ""));
						
						if ( vaProductPartPC != 0.0 && vaARYP != 0.0 && vaRatio != 0.0){
							vnProductionPartNormalTotal = ((Double.parseDouble(vaNormalPC.replaceAll(",", ""))*0.01)+(vaARYP)*0.005)*vaRatio;
							vnNormalTotal = vnProductionPartNormalTotal + vnOrganizationPart;
							
							vnProductionPartRecalTotal = ((Double.parseDouble(vaFeeLookPc.replaceAll(",", ""))*0.01)+(vaARYP)*0.005)*vaRatio;
							vnRecalTotal = vnProductionPartRecalTotal + vnOrganizationPart;
						}								
						voAllOE[i] = vnNormalTotal - vnRecalTotal;
					}
					// render HTML
					for ( int n = 0; n < voGraderList.size() ;n++){
						Map<String, Object> voObject2 = voGraderList.get(n);
						String vaGrader =  voObject2.get("GRADER").toString();
						String vaPersonPerGrader = voObject2.get("PERSON_PER_GRADER").toString();
						int vnMoneyPerPerson = Integer.parseInt( voObject2.get("MONEY_PER_PERSON").toString());
						int vnPersonPerGrader = Integer.parseInt( voObject2.get("PERSON_PER_GRADER").toString());
						int vnMoney = vnMoneyPerPerson / vnPersonPerGrader;
						vaTrOfTable += "<tr><td >"+vaGrader+"</td><td >"+vaPersonPerGrader+"</td><td >"+voDecimalFormat.format(vnMoney)+"</td></tr>";
					}
					// find Net OE
					vnNetOE = vnTotalOE;
					for(int i = 0; i < voAllOE.length ;i++ ){
						vnNetOE = vnNetOE - voAllOE[i];
					}
				}
				
			if ( voGraderList.size() == 0)
				IsEmptyGraderData = "yes";
			
			// check new MM
			if (vbIsNewMm.equals("1")){
				vnTotalOE = 15000;
				vaSpecialOE = "yes";
				vaRemark = "* Special O/E";
			}	
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.close();	
		}
		String vaHtml2 ="" , vaHtml ="";
		PrintWriter voOut = response.getWriter();
		
		// Organization Part
		if ( IsEmptyGraderData.equals("no")){
			vaHtml = "<table class='table-list'>"
					+"<tr>"
						+ "<th width='33%'>Grader</th><th width='32%'>จำนวนคน </th><th width='35%'>เงิน / คน</th>"+
					"</tr>"
					+vaTrOfTable+"</table>";	
		} else {
			vaHtml = "<table class='table-list'>"
					+"<tr>"
						+ "<th width='33%'>Grader</th><th width='32%'>จำนวนคน </th><th width='35%'>เงิน / คน</th>"
					+"</tr>"
					+"<tr>"
						+ "<td colspan='3'> ไม่พบข้อมูล Grader </td>"
				+"</tr>"
					+"</table>";	
		}	
		
		// Production Part
		if ( IsEmptyProductionData.equals("no")){
			vaHtml2 = "<table class='table-list'>"
					+"<tr>"
						+ "<th width='33%'> PC </th><th width='32%'> ARYP(2<sup>nd</sup> ~  5<sup>th</sup>)</th><th width='35%'> Persistency </th>"
					+"</tr>"
					+ "<tr>"
						+ "<td >"+voDecimalFormat.format(vaProductPartPC)+"&nbsp; <i class='fa fa-search' title='ดูรายละเอียด  PC'   onclick='searchData2();'></i></td>"
						+ "<td >"+voDecimalFormat.format(vaARYP)+"</td> "
						+ "<td >"+vaPersistency+"%"+"</td> "
					+"</tr>"
					+"</table>";
		} else {
			vaHtml2 = "<table class='table-list'>"
					+"<tr>"
						+ "<th width='33%'> PC </th><th width='32%'> ARYP(2<sup>nd</sup> ~  5<sup>th</sup>)</th><th width='35%'> Persistency </th>"
					+"</tr>"
					+ "<tr>"
						+ "<td  colspan='3'> ไม่พบข้อมูล Production Part </td>"
					+"</tr>"
					+"</table>";
		}

		JSONObject voObject = new JSONObject();
		JSONArray voArrayData2 = new JSONArray();
		voObject.put("detailsTableRA", vaHtml);
		voObject.put("detailsTableRA2", vaHtml2);
		voObject.put("vnActivePro", vaAcProducerAmount+" คน "+" ("+vaAcProducerMoney+" บาท )");
		voObject.put("vnOrganizationPart", vnOrganizationPart);
		voObject.put("vnTotalOE", voDecimalFormat.format(vnTotalOE));
		voObject.put("vnProductionPart", vnProductionPart);
		voObject.put("IsEmptyGraderData", IsEmptyGraderData);
		voObject.put("isNullData", isNullData);
		voObject.put("vaStatusAllOE", vaStatusAllOE);
		voObject.put("vaSpecialOE", vaSpecialOE);
		voObject.put("vnNetOE", voDecimalFormat.format(vnNetOE));
		voObject.put("vaRemark", vaRemark);
		if (voAllOE != null){
			for ( int i = 0; i < voAllOE.length; i++){
				voArrayData2.add(voDecimalFormat.format(voAllOE[i]));
			}
    		voObject.put("voAllOE",voArrayData2 );
		}
		voOut.print(voObject.toJSONString());
		db.close();
		voOut.close();
    }
    
    @SuppressWarnings("unchecked"  )
    private void getDataTable (HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// columns for sorting data
    	String vaClosYm = "2014";
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaMonth = request.getParameter("sSearch_0").trim();
    	vaClosYm += vaMonth;
		String vaPeNoMm = request.getParameter("sSearch_1").trim();
    	String vaDraw = request.getParameter("sEcho");
		Database db = new Database();
		///
    	int vnTotal = 0, vnTotalAfterFilter = 0;
		SFCAgentStructureDAO voSFCAgentStructureDAO = new SFCAgentStructureDAO(db);
		List<Map<String, Object>> voHeadMmList = null;
		if (vaMonth.equals("") && vaPeNoMm != ""){
			voHeadMmList = voSFCAgentStructureDAO.getHeadMmOfSfcCaseMM(vaPeNoMm);
		} else if (vaMonth != "" && vaPeNoMm.equals("")){
			voHeadMmList = voSFCAgentStructureDAO.getHeadMmOfSfcCaseClosYm(vaClosYm);
		} else if (vaMonth != "" && vaPeNoMm != ""){
			voHeadMmList = voSFCAgentStructureDAO.getHeadMmOfSfcAndCase(vaPeNoMm, vaClosYm);
		}
    	List<Map<String, String>> voListResult =  new ArrayList<Map<String, String>>();
		try {	
			vnTotal = voHeadMmList.size();
			if ( vnAmount == -1){
				for ( int i = 0 ; i < voHeadMmList.size() ; i++){
					Map<String, Object> voObject = voHeadMmList.get(i);
					Map<String, String> voTempData = new HashMap<>();
					voTempData.put("PENO", voObject.get("PE_NO").toString());
					voTempData.put("PENAME", voObject.get("MM_NAME").toString());
					voListResult.add(voTempData);
				}
				vnTotalAfterFilter = vnTotal;
			} else {
				if (voHeadMmList.size() != 0){
					for ( int i = 0 ; i < (vnStart+vnAmount) ; i++){
						Map<String, Object> voObject = voHeadMmList.get(i);
						Map<String, String> voTempData = new HashMap<>();
						voTempData.put("PENO", voObject.get("PE_NO").toString());
						voTempData.put("PENAME", voObject.get("MM_NAME").toString());
						voListResult.add(voTempData);
						if ( i == (voHeadMmList.size() -1 ))
							break;
					}
				}
			    vnTotalAfterFilter = vnTotal;
			}		
		} catch (Exception e) {
			e.getMessage();
		} finally{
			db.close();
		}
		
		PrintWriter out = response.getWriter();    	
		// set sequence
    	int[] vnSequence = new int[voListResult.size()];
    	for (int i = 1; i <= voListResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;    	
    	try {
    		JSONObject voObject = new JSONObject();
    		JSONArray voListata = new JSONArray();
    		for ( int i = 0 ; i < voListResult.size() ; i++){
    			Map<String, String> voTempData = voListResult.get(i);
    			JSONArray voArray = new JSONArray();
    			voArray.add( vnSequence[i]);
    			voArray.add( voTempData.get("PENO"));
    			voArray.add( voTempData.get("PENAME"));
    			voArray.add( voListResult.get(i+vnStart)+"/"+voTempData.get("PENO")+"/"+voTempData.get("PENAME")+"/"+vaClosYm);
    			voListata.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListata);
			out.print(voObject.toJSONString());
		} catch (Exception e) {
			e.getMessage();
		} finally {
			out.close();
		}
    }

    @SuppressWarnings("unchecked"  )
    private void getDataTableDetailPC (HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// columns for sorting data
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaMonth = request.getParameter("sSearch_0").trim();
		String vaPeNoMm = request.getParameter("sSearch_1").trim();
    	String vaDraw = request.getParameter("sEcho");
		Database db = new Database();
		///
    	int vnTotal = 0, vnTotalAfterFilter = 0;
		SFCAgentStructureDAO voSFCAgentStructureDAO = new SFCAgentStructureDAO(db);
		List<Map<String, Object>> voPcDetailList = null;
		voPcDetailList = voSFCAgentStructureDAO.getDetailPC(vaPeNoMm, vaMonth);

    	List<Map<String, String>> voListResult =  new ArrayList<Map<String, String>>();
		try {	
			vnTotal = voPcDetailList.size();
			if ( vnAmount == -1){
				for ( int i = 0 ; i < voPcDetailList.size() ; i++){
					Map<String, Object> voObject = voPcDetailList.get(i);
					Map<String, String> voTempData = new HashMap<>();
					voTempData.put("CLOSYM", voObject.get("CLOS_YM").toString());
					voTempData.put("PENOCOL", voObject.get("PE_NO_COL").toString());
					voTempData.put("PONO", voObject.get("PO_NO").toString());
					String xx1 = voObject.get("AFYP").toString();
					if ( Double.parseDouble(xx1) == 0.00 ){
						voTempData.put("AFYP",  voObject.get("AFYP").toString());
					} else {
						voTempData.put("AFYP", voDecimalFormat.format( Double.parseDouble(  voObject.get("AFYP").toString())));
					}
					String xx = voObject.get("ARYP2").toString();
					if ( Double.parseDouble(xx) == 0.00 ){
						voTempData.put("ARYP2",  voObject.get("ARYP2").toString());
					} else {
						voTempData.put("ARYP2", voDecimalFormat.format( Double.parseDouble(  voObject.get("ARYP2").toString())));
					}
					String xx2 = voObject.get("PC").toString();
					if ( Double.parseDouble(xx2) == 0.00 ){
						voTempData.put("PC",  voObject.get("PC").toString());
					} else {
						voTempData.put("PC", voDecimalFormat.format( Double.parseDouble(  voObject.get("PC").toString())));
					}
					voListResult.add(voTempData);
				}
				vnTotalAfterFilter = vnTotal;
			} else {
				if (voPcDetailList.size() != 0){
					for ( int i = vnStart ; i < (vnStart+vnAmount) ; i++){
						Map<String, Object> voObject = voPcDetailList.get(i);
						Map<String, String> voTempData = new HashMap<>();
						voTempData.put("CLOSYM", voObject.get("CLOS_YM").toString());
						voTempData.put("PENOCOL", voObject.get("PE_NO_COL").toString());
						voTempData.put("PONO", voObject.get("PO_NO").toString());
						String xx1 = voObject.get("AFYP").toString();
						if ( Double.parseDouble(xx1) == 0.00 ){
							voTempData.put("AFYP",  voObject.get("AFYP").toString());
						} else {
							voTempData.put("AFYP", voDecimalFormat.format( Double.parseDouble(  voObject.get("AFYP").toString())));
						}
						String xx = voObject.get("ARYP2").toString();
						if ( Double.parseDouble(xx) == 0.00 ){
							voTempData.put("ARYP2",  voObject.get("ARYP2").toString());
						} else {
							voTempData.put("ARYP2", voDecimalFormat.format( Double.parseDouble(  voObject.get("ARYP2").toString())));
						}
						String xx2 = voObject.get("PC").toString();
						if ( Double.parseDouble(xx2) == 0.00 ){
							voTempData.put("PC",  voObject.get("PC").toString());
						} else {
							voTempData.put("PC", voDecimalFormat.format( Double.parseDouble(  voObject.get("PC").toString())));
						}
						voListResult.add(voTempData);
						if ( i == (voPcDetailList.size() -1 ))
							break;
					}
				}
			    vnTotalAfterFilter = vnTotal;
			}		
		} catch (Exception e) {
			e.getMessage();
		} finally{
			db.close();
		}
		
		PrintWriter out = response.getWriter();    	
		// set sequence
    	int[] vnSequence = new int[voListResult.size()];
    	for (int i = 1; i <= voListResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;    	
    	try {
    		JSONObject voObject = new JSONObject();
    		JSONArray voListata = new JSONArray();
    		for ( int i = 0 ; i < voListResult.size() ; i++){
    			Map<String, String> voTempData = voListResult.get(i);
    			JSONArray voArray = new JSONArray();
    			voArray.add( vnSequence[i]);
    			voArray.add( voTempData.get("CLOSYM"));
    			voArray.add( voTempData.get("PENOCOL"));
    			voArray.add( voTempData.get("PONO"));
    			voArray.add( voTempData.get("AFYP"));
    			voArray.add( voTempData.get("ARYP2"));
    			voArray.add( voTempData.get("PC"));
    			voListata.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListata);
			out.print(voObject.toJSONString());
		} catch (Exception e) {
			e.getMessage();
		} finally {
			out.close();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

}
